#!/usr/bin/ruby -w
require 'rexml/document'
require 'yaml'
$xml = REXML::Document.new(open('config.xml'))
$config = {}
$network = ARGV[0].strip
$config['global'] = {}
$config[$network] = {}
$root = $xml.root
$root.elements.each('global') do |global|
	$config['global']['command_identifier'] = global.elements['command_identifier'].text.to_s
	$config['global']['plugindir'] = global.elements['plugindir'].text.to_s
	if global.elements['plugin_blacklist'].text != nil then
		$config['global']['plugin_blacklist'] = global.elements['plugin_blacklist'].text.split(',')
	else
		$config['global']['plugin_blacklist'] = []
	end
	$config['global']['plugin_data_dir'] = global.elements['plugin_data_dir'].text
end

folder = ARGV[0]

# Fucking /collage/
	@kicks = YAML::load(File.open($config['global']['plugin_data_dir']+'/kicklog.yml'))
	if !@kicks then
		@kicks = {}
	end
	def kick_function(kicker,channel,kicked,message)
		if message.strip.downcase == "bad luck; cheese's fault." then
			kicked = kicked.downcase
			channel = channel.sub('#','').downcase
			if !@kicks[kicked] then @kicks[kicked] = {}; end
			if !@kicks[kicked][channel] then @kicks[kicked][channel] = {}; end
			if !@kicks[kicked][channel][kicker] then @kicks[kicked][channel][kicker] = 0; end
			@kicks[kicked][channel][kicker] = @kicks[kicked][channel][kicker].to_i + 1
			File.open($config['global']['plugin_data_dir']+'/kicklog.yml','w') do |file|
				file << @kicks.to_yaml
			end
		end
	end
	

for file in Dir["#{folder}/*"]
	lines = []
	File.open(file) do |stuff|
		lines = stuff.readlines
	end
	for line in lines
		line = line.sub(/^(.+?)\>\s/,'').strip
		if !line.start_with?('-->') then
			# parsing the line; mostly code copypasted from ircbot.rb's handle_server_input method
			s = line.strip
			s_spaces = s.sub(":","").split
			s_colons = s.split(":")
			if s_colons[1] then
				message = s_colons.join(":").sub(s_colons[1],"").sub("::","")
			else
				message = s_colons.join(":").sub("::","")
			end
			if s_spaces[1] == "KICK" then
				puts s
				if s_spaces[3] == 'cockscockscocks' then
#					send("JOIN #{s_spaces[2]}")
				else	
#					send("NAMES #{s_spaces[2].sub(":","")}")
					kicker	=	s_spaces[0].sub(':','').split('!')[0].downcase.strip
					puts "kicker: '#{kicker}'"
					channel	=	s_spaces[2].downcase.strip
					puts "channel: '#{channel}'"
					kicked	=	s_spaces[3].downcase.strip
					puts "kicked: '#{kicked}'"
					message	=	s.sub("#{s_spaces[0]} #{s_spaces[1]} #{s_spaces[2]} #{s_spaces[3]} :",'').strip.downcase.sub(':','')
					puts "message: '#{message}'"
					kick_function(kicker,channel,kicked,message)
				end
			end
		end
	end
end
